package io.xxx.xbutler.core.check;

import io.xxx.xbutler.data.RoomMapper;
import io.xxx.xbutler.domain.Room;
import io.xxx.xbutler.domain.task.PushContext;
import io.xxx.xbutler.domain.task.Receiver;
import io.xxx.xbutler.domain.task.ReceiverType;
import io.xxx.xbutler.domain.task.Task;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Order(30)
@Component
public class RoomChecker implements Checker {

    @Resource
    private RoomMapper roomMapper;

    @Override
    public CheckError check(PushContext context) {
        Task task = context.getTask();
        Receiver receiver = context.getReceiver();
        Room room = roomMapper.selectById(receiver.getId());
        if (room == null) { // 如果发生，可能是群信息在任务执行过程中被删除了
            CheckError error = CheckError.RoomNotFound;
            log.error("{}[taskId:{}, roomId:{}]", error.getErrorMessage(), task.getId(), receiver.getId());
            return error;
        }

        if (Objects.equals(room.getBusinessUnitId(), task.getBusinessUnitId())) {
            CheckError error = CheckError.RoomBusinessUnitNotMatch;
            log.info("{}[taskId:{}, roomId:{}, taskBusinessUnitId:{}, roomBusinessUnitId:{}]", error.getErrorMessage(), task.getId(), receiver.getId(), task.getBusinessUnitId(), room.getBusinessUnitId());
            return error;
        }
        return null;
    }

    @Override
    public boolean supports(PushContext context) {
        Receiver receiver = context.getReceiver();
        return receiver.getType() == ReceiverType.ROOM;
    }
}
